import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "../../api/axios";
import "./Pass.css";

// 定义医生数据类型
interface Doctor {
  doctorid: number;
  doctorname: string;
  doctordescword: string;
  doctoradmin: string;
  doctoradministre: string;
  doctorbrowse: string;
  doctorcity: string;
  doctorflag: string;
  doctorgood: string;
  doctoriddoc: string;
  doctorimage: string;
  doctorprice: number;
  doctorstate: string;
  doctortime: string;
  nosocomium: string;
  socoadmin: string;
  sococity: string;
  socodescword: string;
  socoid: number;
  socoimage: string;
  socolv: string;
  socostate: string;
}

// 定义API响应类型
interface SearchResponse {
  msg: string;
  total: number;
  data: Doctor[];
}

// 搜索类型枚举
type SearchType = "doctor" | "hospital" | "department" | "disease";

function Index() {
  const navigate = useNavigate();
  const location = useLocation();

  // 搜索相关状态
  const [searchKeyword, setSearchKeyword] = useState("");
  const [searchType, setSearchType] = useState<SearchType>("doctor");
  const [searchResults, setSearchResults] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalCount, setTotalCount] = useState(0);
  const [hasSearched, setHasSearched] = useState(false);

  // 搜索历史
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const HISTORY_KEY = "search_history";

  // 初始化加载本地历史
  useEffect(() => {
    try {
      const raw = localStorage.getItem(HISTORY_KEY);
      if (raw) {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) {
          setSearchHistory(parsed as string[]);
        }
      }
    } catch (e) {
      // 忽略解析错误
    }
  }, []);

  // 历史变更时持久化
  useEffect(() => {
    try {
      localStorage.setItem(HISTORY_KEY, JSON.stringify(searchHistory));
    } catch (e) {
      // 忽略存储错误
    }
  }, [searchHistory]);

  // 热门搜索
  const hotSearches = [
    "感冒",
    "发烧",
    "咳嗽",
    "头痛",
    "失眠",
    "高血压",
    "糖尿病",
    "心脏病",
    "妇产科",
    "儿科",
    "骨科",
    "内科",
    "外科",
    "眼科",
    "皮肤科",
  ];

  // 搜索类型选项
  const searchTypes = [
    { key: "doctor", label: "医生", icon: "👨‍⚕️" },
    { key: "hospital", label: "医院", icon: "🏥" },
    { key: "department", label: "科室", icon: "🏨" },
    { key: "disease", label: "疾病", icon: "💊" },
  ];

  // 从首页搜索框传入的搜索词
  useEffect(() => {
    const state = location.state as { searchKeyword?: string };
    if (state?.searchKeyword) {
      setSearchKeyword(state.searchKeyword);
      handleSearch(state.searchKeyword, "doctor");
    }
  }, [location.state]);

  // 执行搜索
  const handleSearch = async (
    keyword: string,
    type: SearchType = searchType
  ) => {
    if (!keyword.trim()) {
      setError("请输入搜索关键词");
      return;
    }

    setLoading(true);
    setError(null);
    setHasSearched(true);

    try {
      // 根据搜索类型构建不同的搜索参数
      let params: Record<string, string> = {
        pageCode: "1",
        pageSize: "20",
        city: "三门峡市",
      };

      switch (type) {
        case "doctor":
          // 搜索医生：按姓名、科室、医院等搜索
          params.keyword = keyword;
          break;
        case "hospital":
          // 搜索医院：按医院名称搜索
          params.hospitalName = keyword;
          break;
        case "department":
          // 搜索科室：按科室名称搜索
          params.admin = keyword;
          break;
        case "disease":
          // 搜索疾病：按症状、疾病名称搜索
          params.symptom = keyword;
          break;
      }

      const response = await axios.get<SearchResponse>("/doctor/list", {
        params,
      });

      if (response.data.msg === "获取成功") {
        const doctorData = Array.isArray(response.data.data)
          ? response.data.data
          : [response.data.data];

        setSearchResults(doctorData);
        setTotalCount(response.data.total);

        // 添加到搜索历史（置顶、去重、最多10条）
        setSearchHistory((prev) => {
          const filtered = prev.filter((k) => k !== keyword);
          return [keyword, ...filtered].slice(0, 10);
        });

        console.log(`搜索 "${keyword}" 结果:`, doctorData);
      } else {
        setError("搜索失败，请重试");
        setSearchResults([]);
        setTotalCount(0);
      }
    } catch (err) {
      console.error("搜索失败:", err);
      setError("网络请求失败，请检查网络连接");
      setSearchResults([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索提交
  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleSearch(searchKeyword, searchType);
  };

  // 清空搜索输入与结果
  const clearSearch = () => {
    setSearchKeyword("");
    setSearchResults([]);
    setHasSearched(false);
    setError(null);
  };

  // 删除单条历史
  const deleteHistoryItem = (keyword: string) => {
    setSearchHistory((prev) => prev.filter((k) => k !== keyword));
  };

  // 清空全部历史
  const clearHistoryAll = () => {
    setSearchHistory([]);
    try {
      localStorage.removeItem(HISTORY_KEY);
    } catch (e) {}
  };

  // 跳转到医生详情页
  const goToDoctorDetail = (doctor: Doctor) => {
    navigate("/xianqing", { state: { doctorData: doctor } });
  };

  // 跳转到首页
  const goBack = () => {
    navigate("/home");
  };

  return (
    <div className="search-page">
      {/* 搜索头部 */}
      <div className="search-header">
        <div className="search-header-left">
          <button className="back-btn" onClick={goBack}>
            ←
          </button>
          <div className="search-input-container">
            <form onSubmit={handleSearchSubmit}>
              <input
                type="text"
                className="search-input"
                placeholder="搜索医生、医院、科室、疾病症状"
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                autoFocus
              />
              <button type="submit" className="search-btn">
                🔍
              </button>
            </form>
          </div>
        </div>
        {hasSearched && (
          <button className="clear-btn" onClick={clearSearch}>
            清空
          </button>
        )}
      </div>

      {/* 搜索类型选择 */}
      <div className="search-types">
        {searchTypes.map((type) => (
          <button
            key={type.key}
            className={`search-type-btn ${
              searchType === type.key ? "active" : ""
            }`}
            onClick={() => setSearchType(type.key as SearchType)}
          >
            <span className="type-icon">{type.icon}</span>
            <span className="type-label">{type.label}</span>
          </button>
        ))}
      </div>

      {/* 搜索内容区域 */}
      <div className="search-content">
        {!hasSearched ? (
          // 未搜索状态：显示搜索历史和热门搜索
          <div className="search-suggestions">
            {/* 搜索历史 */}
            {searchHistory.length > 0 && (
              <div className="search-section">
                <div className="section-header">
                  <h3>搜索历史</h3>
                  <button
                    className="clear-history-btn"
                    onClick={clearHistoryAll}
                  >
                    清空
                  </button>
                </div>
                <div className="search-tags">
                  {searchHistory.map((keyword, index) => (
                    <div key={index} className="history-item">
                      <button
                        className="history-text"
                        onClick={() => handleSearch(keyword)}
                        title={`搜索 ${keyword}`}
                      >
                        {keyword}
                      </button>
                      <button
                        className="history-delete"
                        onClick={(e) => {
                          e.stopPropagation();
                          deleteHistoryItem(keyword);
                        }}
                        aria-label="删除该历史"
                        title="删除"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 热门搜索 */}
            <div className="search-section">
              <h3>热门搜索</h3>
              <div className="search-tags">
                {hotSearches.map((keyword, index) => (
                  <button
                    key={index}
                    className="search-tag"
                    onClick={() => handleSearch(keyword)}
                  >
                    {keyword}
                  </button>
                ))}
              </div>
            </div>
          </div>
        ) : (
          // 搜索状态：显示搜索结果或错误
          <div className="search-results">
            {loading ? (
              <div className="loading-state">
                <div className="loading-spinner">🔄</div>
                <p>正在搜索...</p>
              </div>
            ) : error ? (
              <div className="error-state">
                <div className="error-icon">❌</div>
                <p>{error}</p>
                <button
                  className="retry-btn"
                  onClick={() => handleSearch(searchKeyword)}
                >
                  重试
                </button>
              </div>
            ) : searchResults.length > 0 ? (
              <div className="results-container">
                <div className="results-header">
                  <h3>搜索结果</h3>
                  <span className="results-count">
                    共找到 {totalCount} 条结果
                  </span>
                </div>

                <div className="results-list">
                  {searchResults.map((doctor) => (
                    <div
                      key={doctor.doctorid}
                      className="result-item"
                      onClick={() => goToDoctorDetail(doctor)}
                    >
                      <div className="doctor-avatar">
                        {doctor.doctorimage ? (
                          <img
                            src={doctor.doctorimage}
                            alt={doctor.doctorname}
                            className="avatar-img"
                          />
                        ) : (
                          <div className="default-avatar">👨‍⚕️</div>
                        )}
                      </div>

                      <div className="doctor-info">
                        <div className="doctor-name">
                          {doctor.doctorname}
                          <span className="doctor-title">
                            {doctor.doctorstate}
                          </span>
                        </div>
                        <div className="doctor-hospital">
                          {doctor.nosocomium} - {doctor.doctoradministre}
                        </div>
                        <div className="doctor-expertise">
                          擅长: {doctor.doctordescword}
                        </div>
                        <div className="doctor-stats">
                          <span className="rating">
                            好评率 {doctor.doctorgood}%
                          </span>
                          <span className="separator">|</span>
                          <span className="views">
                            浏览 {doctor.doctorbrowse}
                          </span>
                          <span className="separator">|</span>
                          <span className="price">¥{doctor.doctorprice}起</span>
                        </div>
                      </div>

                      <div className="result-arrow">→</div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="no-results">
                <div className="no-results-icon">🔍</div>
                <h3>未找到相关结果</h3>
                <p>试试其他关键词或搜索类型</p>
                <button className="retry-btn" onClick={clearSearch}>
                  重新搜索
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

export default Index;
